//
//  NewFeatureViewController.swift
//  MySinaWeibo
//
//  Created by apple on 15/11/7.
//  Copyright © 2015年 baidu. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureViewController: UICollectionViewController {
    
    /// 图像总数
    private let imageCount = 4
    private let layout = LNFlowLayout()
    
    //    没有override,因为collectionView的指定的构造函数是带layout的
    init() {
        
        super.init(collectionViewLayout: layout)
    }
    

    required init?(coder aDecoder: NSCoder) {
//        本类禁止用sb 代发， - 纯代码开发，考虑因素少，风险小
        
//        fatalError("init(coder:) has not been implemented")
//        本类允许用sb开发，有些公司是混合开发，需要考虑的因素多，都需要测试才行。
        super.init(coder: aDecoder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
       
        
        

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }




    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
    
        // Configure the cell
        cell.imageIndex = indexPath.item
    
        return cell
    }
    
    /// 完成显示 cell - indexPath是之前消失 cell 的indexPath
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        
//        获取当前显示的 indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
//        判断是否是末尾的 indexPath
        if path.item == imageCount - 1 {
        
//            播放动画
            let cell = collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell
            cell.startButtonAnim()
            
            
        }
        
    }
    

}


/// 新特性 cell
class NewFeatureCell: UICollectionViewCell {
    
    /// 图像索引
    private var imageIndex: Int = 0 {
    
        didSet {
            
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            startButton.hidden = true
        }
    }
    
/// 开始体验
    func    clickStartButton() {
    
        NSNotificationCenter.defaultCenter().postNotificationName(LNRootViewControllerSwitchNotification, object: true)
    }
    
/// 开始按钮动画
    private func startButtonAnim() {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
//        禁止按钮操作
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
//            恢复默认形变
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
//                启用按钮点击
                self.startButton.userInteractionEnabled = true
        }
    }
    
    
//    MARK: - 设置UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }
   

    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        prepareUI()
    }
    
    private func prepareUI() {
        
        
        //    添加控件 - 建议都加载contentView上
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
//        自动布局
        iconView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview": iconView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: ["subview": iconView]))
        
        startButton.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
        
    }
//    MARK: - 懒加载控件
    private lazy var iconView = UIImageView()
    private lazy var startButton: UIButton = {
    
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.sizeToFit()
        
//        提示：按钮的隐藏属性会因为复用工作不正常
        button.hidden = true
        button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        return button
    }()
}


/// 自定义流水布局
private class LNFlowLayout: UICollectionViewFlowLayout {

    private override func prepareLayout() {
//        print(collectionView)
        itemSize = collectionView!.bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
}












































